package com.applancer.fragment;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;

import uk.co.senab.actionbarpulltorefresh.library.ActionBarPullToRefresh;
import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout;
import uk.co.senab.actionbarpulltorefresh.library.listeners.OnRefreshListener;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;

import com.applancer.adapter.FeedAdapter;
import com.applancer.dataprovider.DataType.Type;
import com.applancer.delegate.NewFeedDelegate;
import com.applancer.model.FeedModel;
import com.applancer.model.GeneralModel;
import com.applancer.nativecmsflip.FeedDetailActivity;
import com.applancer.nativecmsflip.R;
import com.applancer.parser.GeneralParser;
import com.applancer.provider.StringUtils;
import com.loopj.android.http.AsyncHttpResponseHandler;

public class FeedNormalFragment extends FeedGeneralFragment implements
		OnRefreshListener {

	protected NewFeedDelegate delegate;
	protected ListView listView;
	protected FeedAdapter adapter;
	protected List<GeneralModel> listData;
	protected Boolean loadingMore = false;
	protected String title;
	protected ProgressBar indicator_loading_feed;
	protected ImageButton indicator_refresh_feed;
	private PullToRefreshLayout mPullToRefreshLayout;
	protected int topmostListView;

	public FeedNormalFragment(String i, String title, NewFeedDelegate del) {

		delegate = del;
		id = i;
		this.title = title;

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		contentView = inflater.inflate(R.layout.feed_normal_fragment, null);
		return contentView;

	}

	@Override
	protected void initial() {
		super.initial();

		listData = new ArrayList<GeneralModel>();
		adapter = new FeedAdapter(contentView.getContext(), listData);
		listView = (ListView) contentView.findViewById(R.id.list_feed);
		indicator_loading_feed = (ProgressBar) contentView
				.findViewById(R.id.indicator_loading_feed);
		indicator_refresh_feed = (ImageButton) contentView
				.findViewById(R.id.indicator_refresh_feed);

		parser = GeneralParser.createInstance(Type.Post);
		mPullToRefreshLayout = (PullToRefreshLayout) contentView
				.findViewById(R.id.ptr_layout);

	}

	@Override
	protected void execution() {
		super.execution();

		ActionBarPullToRefresh.from(getActivity())
				.theseChildrenArePullable(listView)
				.listener(FeedNormalFragment.this).setup(mPullToRefreshLayout);

		listView.setOnItemClickListener(itemClick);
		listView.setVerticalScrollBarEnabled(false);
		listView.setOnScrollListener(scrollListener);

		listView.setAdapter(adapter);

		fitListView();

		indicator_refresh_feed.setOnClickListener(refreshClick);

		indicator_loading_feed.setVisibility(View.VISIBLE);
		indicator_refresh_feed.setVisibility(View.GONE);
		getFeed();

	}

	public void onConfigurationChanged(Configuration newConfig) {
		fitListView();
	};

	OnClickListener refreshClick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			indicator_loading_feed.setVisibility(View.VISIBLE);
			indicator_refresh_feed.setVisibility(View.GONE);
			(new Handler()).postDelayed(new Runnable() {

				@Override
				public void run() {
					getFeed();
				}
			}, 2000);
		}
	};

	private void fitListView() {
		int currentapiVersion = android.os.Build.VERSION.SDK_INT;
		boolean hasMenuKey = ViewConfiguration.get(contentView.getContext())
				.hasPermanentMenuKey();
		if (currentapiVersion >= 19) {
			Resources r = getResources();
			int px = (int) r.getDimension(R.dimen.padding_materio);
			int statusbar_heigh = StringUtils.getStatusBarHeight(getActivity());
			int actionbar_heigh = StringUtils.getActionbarHeight(getActivity());

			topmostListView = px + statusbar_heigh + actionbar_heigh;
			listView.setPadding(
					px,
					topmostListView,
					px,
					px
							+ (!hasMenuKey ? StringUtils
									.getNavigationBarHeigh(getActivity()) : 0));

		}
	}

	OnItemClickListener itemClick = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {

			Intent intent = new Intent(contentView.getContext(),
					FeedDetailActivity.class);

			ArrayList<FeedModel> lmodeldata = new ArrayList<FeedModel>();
			for (int i = 0; i < listData.size(); i++) {
				lmodeldata.add((FeedModel) listData.get(i));
			}

			intent.putExtra("lmodel", lmodeldata);
			intent.putExtra("index", position);
			intent.putExtra("title", title);

			contentView.getContext().startActivity(intent);
			if (getActivity() != null)
				getActivity().overridePendingTransition(R.anim.slide_left_in,
						R.anim.slide_left_out);
		}
	};

	OnScrollListener scrollListener = new OnScrollListener() {

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {

		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {

			if (firstVisibleItem == 0) {
				View viewChild = listView.getChildAt(0);
				if (viewChild != null) {
					int i = viewChild.getTop();

					if (i == topmostListView) {
						mPullToRefreshLayout.setEnabled(true);
					} else {
						mPullToRefreshLayout.setEnabled(false);
					}
				}

			}

			int lastInScreen = firstVisibleItem + visibleItemCount;
			if ((lastInScreen == totalItemCount) && !(loadingMore)
					&& listData.size() > 0) {
				getFeed();
			}

		}
	};

	AsyncHttpResponseHandler handler = new AsyncHttpResponseHandler() {
		public void onStart() {

		};

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] response) {
			indicator_loading_feed.setVisibility(View.GONE);
			String result = new String(response);

			List<GeneralModel> newData = parser.parseData(result);

			if (newData.size() == 0)
				return;

			listData.addAll(newData);
			adapter.notifyDataSetChanged();

			loadingMore = false;
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
			if (listData.size() == 0)
				indicator_refresh_feed.setVisibility(View.VISIBLE);

		}

		public void onFinish() {
			if (indicator_loading_feed.getVisibility() == View.VISIBLE)
				indicator_loading_feed.setVisibility(View.GONE);
		};

	};

	public void getFeed() {
		loadingMore = true;
		Log.d(this.getClass().toString(),
				"getFeed" + "with size : " + listData.size());

		if (!dataProvider.getFeed(id, listData.size() + "", handler)
				&& listData.size() == 0) {
			indicator_loading_feed.setVisibility(View.GONE);
			indicator_refresh_feed.setVisibility(View.VISIBLE);
		}
	}

	public void refreshFeed() {
		dataProvider.getFeed(id, "0", refreshHandler);
	}

	@Override
	public void onRefreshStarted(View view) {
		viewPagerCallback.onFreezeViewPager();
		refreshFeed();

	}

	AsyncHttpResponseHandler refreshHandler = new AsyncHttpResponseHandler() {
		public void onStart() {

		};

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] response) {
			String result = new String(response);

			List<GeneralModel> newData = parser.parseData(result);

			if (newData.size() == 0)
				return;

			listData.clear();
			listData.addAll(newData);
			adapter.notifyDataSetChanged();

		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {

		}

		public void onFinish() {
			indicator_loading_feed.setVisibility(View.GONE);
			mPullToRefreshLayout.setRefreshComplete();
			viewPagerCallback.onReleaseViewPager();
		};

	};
}
